
using Youz.Common.Helper;
using Youz.Common.DAL;
using Youz.Common.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections;

namespace Youz.Common.BLL
{
    /// <summary>
    /// Lang_Language BLL Class
    /// </summary>
    public partial class Lang_LanguageBLL : BaseBLL
    {
        private static Lang_LanguageDAL dal = new Lang_LanguageDAL();

        private const string CK_Language_All = "CK_Langage_All";
        private const string CK_Language_JS = "CK_Language_JS";

        private static string Current_CK_Langage_All 
        {
            get
            {
                return string.Format("{0}_{1}", CK_Language_All, (int)Utility.CurrentSiteLanguageID);
            }
        }

        private static string Current_CK_Language_JS
        {
            get
            {
                return string.Format("{0}_{1}", CK_Language_JS, (int)Utility.CurrentSiteLanguageID);
            }
        }

        public Lang_LanguageBLL()
        {
            base.ModuleName = "Lang_Language";
            base.MenuName = "Lang_Language";
		}
        
        #region  成员方法
        public static DataTable Gets(string strWhere)
        {
            return dal.Gets(strWhere);
        }

        public static Hashtable Gets()
        {
            Hashtable ht = CacheHelper.GetCache(Current_CK_Langage_All) as Hashtable;

            if (ht == null)
            {
                ht = new Hashtable();
                string key = string.Empty;

                DataTable dt = Gets(string.Format(" WebSite={0} ", (int)Utility.CurrentSiteLanguageID));
                foreach (DataRow item in dt.Rows)
                {
                    //ModuleName+LanguageKey+LanguageCode 作为KEY
                    key = (item["ModuleName"].ToString() + "_" + item["LanguageKey"].ToString() + "_" + item["LanguageCode"].ToString()).ToLower();
                    if (!ht.ContainsKey(key))
                    {
                        ht.Add(key, item["LanguageValue"]);
                    }
                }

                CacheHelper.SetCache(Current_CK_Langage_All, ht);
            }

            return ht;
        }

        /// <summary>
        /// 获取网站【后台】多语言数据
        /// </summary>
        public static string LanguageByManage(LanguageModule module, string key, string value)
        {
            return Get(Convert.ToString(module), key, value);
        }

        /// <summary>
        /// 获取网站【后台】多语言数据
        /// </summary>
        public static string LanguageByManage(LanguageModule module, string key)
        {
            return LanguageByManage(module, key, string.Empty);
        }

        /// <summary>
        /// 获取网站【前台】多语言数据
        /// </summary>
        public static string LanguageByWebSite(LanguageModule module, string key, string value)
        {
            return Get(Convert.ToString(module), key, value);
        }

        /// <summary>
        /// 获取网站【前台】多语言数据
        /// </summary>
        public static string LanguageByWebSite(LanguageModule module, string key)
        {
            return LanguageByWebSite(module, key, string.Empty);
        }

        public static string Get(string module, string key)
        {
            Hashtable htLanguageManage = Gets();

            if (htLanguageManage != null)
            {
                string value = htLanguageManage[(module + "_" + key + "_" + Utility.CurrentLanguage).ToLower()] as String;
                return string.IsNullOrEmpty(value) ? string.Empty : value;
            }
            else
                return string.Empty;
        }

        public static string Get(string module, string key, string language)
        {
            string value = Get(module, key);

            if (string.IsNullOrEmpty(value))
            {
                language = string.IsNullOrEmpty(language) ? key : language;
                Lang_Language lan = new Lang_Language();
                lan.ModuleName = Convert.ToString(module);
                lan.LanguageKey = key;
                lan.LanguageValue = language;
                lan.WebSite = Utility.CurrentSiteLanguageID;

                new Lang_LanguageBLL().AddBatch(lan);

                return language;
            }
            else
            {
                return value;
            }
        }

        /// <summary>
        /// 获取JS的多语言
        /// </summary>
        /// <returns></returns>
        public static string GetJS()
        {
            Hashtable ht = CacheHelper.GetCache(Current_CK_Language_JS) as Hashtable;
            StringBuilder sb = new StringBuilder();

            if (ht == null)
            {
                ht = new Hashtable();
                DataTable dt = Gets(string.Format(" WebSite={0} and ModuleName='{1}' ", (int)Utility.CurrentSiteLanguageID, "M_JS"));
                foreach (DataRow item in dt.Rows)
                {
                    if (!ht.ContainsKey(item["LanguageCode"]))
                    {
                        sb = new StringBuilder();
                        ht.Add(item["LanguageCode"], sb);
                    }
                    else
                    {
                        sb = ht[item["LanguageCode"]] as StringBuilder;
                    }
                    sb.AppendFormat("'{0}':'{1}',", item["LanguageKey"].ToString().Trim(), item["LanguageValue"].ToString().Replace("'", "\\'"));
                    ht[item["LanguageCode"]] = sb;
                }

                CacheHelper.SetCache(Current_CK_Language_JS, ht);
            }

            sb = ht[Utility.CurrentLanguage] as StringBuilder;

            StringBuilder js = new StringBuilder();
            js.Append("var languages = {");
            js.Append(sb == null ? string.Empty : sb.ToString());
            js.Append("};");
            js.Append("function R(key, value) { return r(key, value); };");
            js.Append("function r(key, value) {");
            js.Append("    key = key.replace(/[-\\.]/gi, '_'); var v = eval('languages.' + key);");
            js.Append("    if (v) {");
            js.Append("        return v;");
            js.Append("    }");
            js.Append("    else {");
            js.Append("        if(value) {");
            js.Append("           addLanguage(key, value);");
            js.Append("           return value;}");
            js.Append("        else { return key; }");
            js.Append("    }");
            js.Append("}");
            js.Append("function addLanguage(key, value) {");
            js.Append("     $.post(\"/Ajax/JSLanguage.ashx?type=add\", {Key:key, Value:value});");
            js.Append("}");

            js.Append("function changeLanguage(LanguageValue) {");
            js.Append(" $.post('/Ajax/JSLanguage.ashx?type=change', { LanguageKey: LanguageValue }, function (data) {");
            js.Append("     window.location.reload();");
            js.Append(" });");
            js.Append("}");
            return js.ToString();
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string ModuleName, string LanguageKey, SiteType WebSite)
        {
            return dal.Exists(ModuleName, LanguageKey, WebSite);
        }

        public bool Exists(Lang_Language model)
        {
            return dal.Exists(model);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(Lang_Language model)
        {
            if (Exists(model))
            {
                return false;
            }

            model.LanguageKey = model.LanguageKey.Trim();

            var r = dal.Add(model);

            if(r)
            {
                RemoveCache();
            }

            base.WriteOperationLog(OperationType.Add, r, Utility.GetJsonByObjectHaveTime(model));

            return r;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="model"></param>
        public void AddBatch(Lang_Language model)
        {
            List<Lang_LanguageType> list = new Lang_LanguageTypeBLL().Gets();

            foreach (Lang_LanguageType item in list)
            {
                model.LanguageCode = item.LanguageCode;

                this.Add(model);
            }
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        private void RemoveCache()
        {
            var array = Enum.GetValues(typeof(SiteType));
            foreach (int value in array)
            {
                CacheHelper.RemoveCache(string.Format("{0}_{1}", CK_Language_All, value));
                CacheHelper.RemoveCache(string.Format("{0}_{1}", CK_Language_JS, value));
            }
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Lang_Language model)
        {
            //更新前先判断是否存在，不存在则先添加
            if (Exists(model))
            {
                var r = dal.Update(model);

                if(r)
                {
                    RemoveCache();
                }

                base.WriteOperationLog(OperationType.Update, r, Utility.GetJsonByObjectHaveTime(model));

                return r;
            }
            else
            {
                return this.Add(model);
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string ModuleName, string LanguageKey)
        {
            var r = dal.Delete(ModuleName, LanguageKey);

            if(r)
            {
                RemoveCache();
            }

            base.WriteOperationLog(OperationType.Delete, r, string.Format("ModuleName={0} LanguageKey={1}", ModuleName, LanguageKey));

            return r;
        }

        /// <summary>
        /// 获取语言模块
        /// </summary>
        /// <param name="site"></param>
        /// <returns></returns>
        public List<string> GetModule(SiteType site)
        {
            return dal.GetModules(site);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        /// <param name="site"></param>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public DataTable GetList(SiteType site, string strWhere)
        {
            strWhere = GetSiteTypeSql(site, strWhere);

            return dal.GetList(strWhere);
        }

        /// <summary>
        /// 获得数据列表(分页查找条件)
        /// </summary>
        public DataTable GetList(SiteType site, string strWhere, int pageindex, int pagesize, out int total)
        {
            strWhere = GetSiteTypeSql(site, strWhere);

            return dal.GetList(strWhere, pageindex, pagesize, out total);
        }

        private string GetSiteTypeSql(SiteType site, string strWhere)
        {
            string sqlSite = string.Format(" WebSite={0} ", (int)site);
            if (string.IsNullOrEmpty(strWhere))
            {
                strWhere = sqlSite;
            }
            else
            {
                strWhere += " and " + sqlSite;
            }

            return strWhere;
        }
        #endregion  成员方法
    }
}


  